package me.wangqu.weiyouqu.web.rest.business.dao.impl;

import me.wangqu.weiyouqu.web.rest.business.dao.WithDrawDao;
import me.wangqu.weiyouqu.web.rest.business.model.WithdrawAccount;
import me.wangqu.weiyouqu.web.rest.business.model.WithdrawModel;
import me.wangqu.weiyouqu.web.rest.util.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by joln on 2016/6/25.
 */
@Repository
public class WithDrawDaoImpl implements WithDrawDao {
    private final Logger log = LoggerFactory.getLogger(WithDrawDaoImpl.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public WithdrawAccount getSelfCashAccount(String login) {
        log.debug("获取账户余额及支付宝信息");
        if (!ObjectUtils.isEmpty(login)) {
            StringBuffer sql = new StringBuffer(512);
            List<String> params = new ArrayList<String>();
            sql.append("SELECT u.money as balance, u.realname as realname, u.alipay as alipay from userdata u where u.phone = ?");
            params.add(login);
            return jdbcTemplate.queryForObject(sql.toString(), params.toArray(), new RowMapper<WithdrawAccount>() {
                @Override
                public WithdrawAccount mapRow(ResultSet resultSet, int i) throws SQLException {
                    WithdrawAccount account = new WithdrawAccount();
                    account.setAlipay(resultSet.getString("alipay"));
                    account.setBalance(BigDecimal.valueOf(resultSet.getDouble("balance")));
                    account.setRealName(resultSet.getString("realname"));

                    return account;
                }
            });
        }

        return null;
    }

    @Override
    public List<WithdrawModel> getSelfWithdraws(String login, Pageable pageable) {
        log.debug("获取提现列表");
        if (!ObjectUtils.isEmpty(pageable)) {
            StringBuffer sql = new StringBuffer();
            List<Object> params = new ArrayList<>();
            sql.append("SELECT ");
            sql.append("    t.money AS amount,");
            sql.append("    t.type AS type,");
            sql.append("    t.realname AS realName,");
            sql.append("    IFNULL(t.alipay, t.wx) AS account,");
            sql.append("    FROM_UNIXTIME(t.time, '%Y-%m-%d %H:%i:%S') AS time,");
            sql.append("    t.state AS status");
            sql.append(" FROM");
            sql.append("    txdata t");
            sql.append(" WHERE");
            sql.append("    t.phone = ?");
            sql.append(" LIMIT ? , ?");
            params.add(login);
            params.add(pageable.getOffset());
            params.add(pageable.getPageSize());
            return jdbcTemplate.query(sql.toString(), params.toArray(), new RowMapper<WithdrawModel>() {
                @Override
                public WithdrawModel mapRow(ResultSet rt, int i) throws SQLException {
                    WithdrawModel w = new WithdrawModel();
                    w.setAccount(rt.getString("account"));
                    w.setAmount(BigDecimal.valueOf(rt.getDouble("amount")));
                    w.setStatus(rt.getInt("status"));
                    w.setTime(rt.getString("time"));
                    w.setType(rt.getInt("type"));
                    w.setRealName(rt.getString("realName"));
                    return w;
                }
            });
        }
        return null;
    }

    @Override
    public boolean isSelfRealName(String login) {
        log.debug("判断是否设置支付宝真实姓名");
        if (!ObjectUtils.isEmpty(login)) {
            StringBuffer sql = new StringBuffer();
            List<String> params = new ArrayList<>();
            sql.append("SELECT realname FROM userdata WHERE phone=? limit 1");
            params.add(login);
            return !StringUtils.isEmpty(jdbcTemplate.queryForObject(sql.toString(), params.toArray(), String.class));


        }
        return false;
    }

    @Override
    public boolean setSelfCashAccount(WithdrawModel model, String login) {
        log.debug("设置帐户信息");
        if (!ObjectUtils.isEmpty(model)) {
            StringBuffer sql = new StringBuffer();
            List<String> params = new ArrayList<>();
            sql.append("UPDATE userdata SET realname=?,alipay=? WHERE phone=? ");
            params.add(model.getRealName());
            params.add(model.getAccount());
            params.add(login);
            return jdbcTemplate.update(sql.toString(), params.toArray()) > 0;
        }
        return false;
    }

    @Override
    public boolean postSelfWithdraw(WithdrawModel model, String login) {
        if (ObjectUtils.isEmpty(login) || ObjectUtils.isEmpty(model) || ObjectUtils.isEmpty(model.getAmount())
            || ObjectUtils.isEmpty(model.getType())) {
            return false;
        }
        StringBuffer sql = new StringBuffer();
        List<Object> params = new ArrayList<>();
        // 调整帐户信息
        sql.append("UPDATE userdata u ");
        sql.append(" SET ");
        sql.append("    u.money = u.money - ?,");
        sql.append("    u.expenditure = u.expenditure + ?");
        sql.append(" WHERE");
        sql.append("    u.phone = ?");
        params.add(model.getAmount());
        params.add(model.getAmount());
        params.add(login);
        if (jdbcTemplate.update(sql.toString(), params.toArray()) > 0) {
            // 增加提现申请记录
            sql = new StringBuffer();
            params = new ArrayList<>();
            sql.append("insert into `txdata` (`uid`, `sx1`, `phone`, `type`, `realname`, `alipay`, `wx`, `money`, `state`, `time`)");
            sql.append("SELECT ");
            sql.append("    u.id,");
            sql.append("    u.tj_id,");
            sql.append("    u.phone,");
            sql.append("    ?,");
            sql.append("    u.realname,");
            sql.append("    u.alipay,");
            sql.append("    u.wx,");
            sql.append("    ?,");
            sql.append("    ?,");
            sql.append("    UNIX_TIMESTAMP()");
            sql.append(" FROM");
            sql.append("    userdata u");
            sql.append(" WHERE");
            sql.append("    u.phone = ?");
            params.add(Constant.ACCOUNT_TYPE_ZHIFUBAO);
            params.add(model.getAccount());
            params.add(Constant.ACCOUNT_WITHDRAW_STATUS_PROGRESS);
            params.add(login);
            return jdbcTemplate.update(sql.toString(), params.toArray()) > 0;
        }
        return false;
    }
}
